類型 | 說明 | 檔案位置 |
---|---|---|
單元測試 | 測試單一函式/模組邏輯 | mod tests {} 內嵌在模組中 |
整合測試 | 模擬外部使用情境 | tests/ 目錄下 |
範例測試 | 測試 doc code examples | /// 註解中寫 code |
// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
}
建立 tests/ 目錄:
mkdir tests
// tests/integration_test.rs
use my_crate::add;
#[test]
fn test_add_integration() {
assert_eq!(add(10, 5), 15);
}
注意:
/// Adds two numbers.
/// ```
/// use my_crate::add;
/// assert_eq!(add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
cargo test 會自動執行文件中所有 /// 包含的測試程式碼。
cargo test # 執行所有測試
cargo test test_add # 執行指定測試
cargo test -- --nocapture # 顯示 println! 輸出
assert!(cond); // 為 true
assert_eq!(a, b); // 相等
assert_ne!(a, b); // 不相等
assert!(result.is_ok()); // Result::Ok
assert!(result.is_err()); // Result::Err
# Cargo.toml
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
#[tokio::test]
async fn test_async_logic() {
let result = async_fn().await;
assert_eq!(result, 42);
}
先放上